//
//  EKEventStore+Extension.m
//  YSUtils
//
//  Created by edz on 2021/4/11.
//  Copyright © 2021 Apple. All rights reserved.
//

#import "EKEventStore+Extension.h"

NSString * const YSEventStoreErrorDomain = @"co.yueshang.event.store.error";

@implementation EKEventStore (Extension)
- (void)ys_saveEvent:(EKEvent *)event span:(EKSpan)span completion:(void (^)(NSError * _Nonnull))completion {

    EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
    
    switch (status) {
        case EKAuthorizationStatusNotDetermined:
            [self ys_requestAccessAndSaveEvent:event span:span completion:completion];
            break;
        case EKAuthorizationStatusRestricted:
            completion ?: completion([NSError errorWithDomain:YSEventStoreErrorDomain code:YSEventStoreErrorAuthorizationRestricted userInfo:nil]);
            break;
        case EKAuthorizationStatusDenied:
            completion ?: completion([NSError errorWithDomain:YSEventStoreErrorDomain code:YSEventStoreErrorAuthorizationDenied userInfo:nil]);
            break;
        case EKAuthorizationStatusAuthorized:{
            NSError *error = nil;
            [self saveEvent:event span:span error:&error];
            completion ?: completion(error);
            break;
        }
    }
}

- (void)ys_requestAccessAndSaveEvent:(EKEvent *)event span:(EKSpan)span completion:(void (^)(NSError * nullable))completion {
    [self requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (error)  {
            completion ?: completion(error);
            return;
        }
        if (!granted) {
            completion ?: completion([NSError errorWithDomain:YSEventStoreErrorDomain code:YSEventStoreErrorAuthorizationDenied userInfo:nil]);
            return;
        }
        NSError *saveError = nil;
        [self saveEvent:event span:EKSpanThisEvent error:&saveError];
        completion ?: completion(saveError);
    }];
}
@end
